<template>
  <div style="position: absolute; height: 55%; top: 10%; left: 10%">
    <div style="font-size: 16px; translate: -50% 0; color: white">
      PD:{{ props.marks[currentIndex!].label }}
    </div>
    <div
      class="slider-track"
      ref="track"
      @mousedown.prevent="(mousedown(), onMove($event))"
      @touchstart.prevent="(mousedown(), onMove($event))"
      style="position: relative; width: 4px; height: 100%; background: rgba(255, 255, 255, 0.5)"
    >
      <div
        class="slider-fill"
        style="width: 100%; position: absolute; bottom: 0"
        :style="{ height: fillHeight + '%', background: props.sliderColor }"
      ></div>
      <div
        class="slider-thumb"
        style="
          width: 20px;
          height: 20px;
          border-radius: 50%;
          position: absolute;
          left: 50%;
          transform: translate(-50%, 50%);
        "
        @mousedown.prevent="mousedown"
        @touchstart="mousedown"
        :style="{ bottom: fillHeight + '%', background: sliderColor }"
      ></div>
    </div>
  </div>
</template>
<script setup lang="ts">
import type { PdDefault } from '@type/index'
import { config } from '@/try-on/config'
import { computed, ref } from 'vue'
import { TryOn } from '@/try-on'
const props = withDefaults(
  defineProps<{
    marks?: PdDefault[]
    modelValue: number
    sliderColor: string
  }>(),
  {
    marks: () => config.tryOn.pdScale,
  },
)
const track = ref<HTMLDivElement>()
const { marks } = props
const fillHeight = computed(() => (currentIndex.value! / (marks.length - 1)) * 100)
const currentIndex = defineModel<number>()
function mousedown() {
  window.addEventListener('mousemove', onMove, { passive: false })
  window.addEventListener('mouseup', onUp)
  window.addEventListener('touchmove', onMove, { passive: false })
  window.addEventListener('touchend', onUp)
}
function onMove(em: MouseEvent | TouchEvent) {
  em.preventDefault()
  let clientY = 0
  if (em instanceof MouseEvent) {
    clientY = em.clientY
  } else {
    clientY = em.touches[0].clientY
  }
  const rect = track.value!.getClientRects()[0]
  const percent = Math.min(Math.max((rect.bottom - clientY) / rect.height, 0), 1)
  const idx = Math.round(percent * (marks.length - 1))
  if (idx !== currentIndex.value) {
    currentIndex.value = idx
    TryOn.scene.glasses?.zoomGlasses(props.marks[idx].value)
    TryOn.scene.debug?.pdSlider.setValue(Number(props.marks[idx].label))
  }
}
function onUp() {
  window.removeEventListener('mousemove', onMove)
  window.removeEventListener('mouseup', onUp)
}
</script>
<style lang="scss"></style>
